import Vue from 'vue';
import axios from 'axios';
import router from '../router';
const ENV_SUFFIX = process.env.NODE_ENV === 'production'
  ? location[('111h11' + 1 + '11o22' + 1 + '221s11' + 1 + '1t22').replace(/\d+/g, '')].split('.')[1]
  : 'zhongjianedu';

const $this = Vue.prototype;
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/axios/' : '';
//封装
axios.paramPost = function (url, data) {
  return this({
    url,
    data,
    method: 'post',
    transformRequest: data => data && data.toParams(),
  });
};
//拦截器
const decorator_resource_info = (data) => {
  if (!ENV_SUFFIX) return '';

  data['timestamp'] = Math.ceil(new Date() / 1000);
  //sort key
  const reverse_key = Object.keys(data).sort();
  let resource_code = reverse_key.reduce((rst, v) => rst += `${v}=${ data[v]}&`, '').slice(0, -1) + ENV_SUFFIX;
  data['sign'] = $this.$md5(resource_code);

};
axios.interceptors.request.use(
  request => {
    if (request.data.transFormData) {
      const transFormData = request.data.transFormData,
        transFormData_filter_keys = request.data.transFormData_filter_keys || [];//很少用
      delete request.data.transFormData, delete request.data.transFormData_filter_keys;
      //增加资源code
      decorator_resource_info(request.data);
      request.data = request.data.toFormData(transFormData, ['timestamp', 'sign', ...transFormData_filter_keys]); //toFormData 第二个参数为不处理的 , 改来改去渣了
    } else {
      //增加资源code
      decorator_resource_info(request.data);
    }
    request.data.user_id = router.history.current.query.user_id || ''
    request.data.openid = router.history.current.query.openid || ''
    // request.data.openid ='ompDU5L6EilzrYTT432yZmTfjOHk'
    return request;
  },
);
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (axios.isCancel(error)) {
      return Promise.resolve({data: error.message});
    } else {
      $this.$toast.fail(error.message);
    }
  },
);
const $api = require('./api').default;

Vue.prototype.$api = $api;


/* methods */
function getCacheCodeByRequest(config) {
  return (config.url + encodeURI(JSON.stringify(config.data))).replace(/\W+/g, '');//fix 汉字
}



